<template>
  <div>
    <!-- 面包屑-->
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-card>
      <el-row>
        <el-alert
          :closable='false'
          show-icon
          title='提示: 只能为第三级分类设置属性'
          type='warning'>
        </el-alert>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <span style='margin-right: 20px'>选择商品</span>
        <el-cascader v-model='casShopKey'
                     :options='shopList'
                     :props='shopOption'
                     clearable
                     @change='casShopKeys'
        ></el-cascader>
      </el-row>
      <el-row>
        <el-tabs v-model='tabActive' @tab-click='tabsClick'>
          <!-- 动态参数 -->
          <el-tab-pane label='动态参数' name='many'>
            <el-button type='primary' :disabled='btnDisable' size='small' @click='addParamsPull'>添加参数</el-button>
            <div class='row-table'>
              <!-- 动态数据表格 -->
              <el-table :data='DynamicData' border stripe>
                <el-table-column type='expand'>
                  <template v-slot='scope'>
                    <el-tag v-for='(item,i) in scope.row.attr_vals' :key='i' closable @close='delTag(i,scope.row)'>
                      {{ item }}
                    </el-tag>
                    <!-- 动态生成一个属性节点 -->
                    <el-input
                      class='input-new-tag'
                      v-if='scope.row.inputTagVisible'
                      v-model='scope.row.inputTagValue'
                      ref='saveTagInput'
                      size='small'
                      @keyup.enter.native='InputTagConfirm(scope.row)'
                      @blur='InputTagConfirm(scope.row)'
                    >
                    </el-input>
                    <el-button v-else size='small' @click='showInputTag(scope.row)'>+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column label='#' type='index' align='center'></el-table-column>
                <el-table-column label='参数名称' align='center' prop='attr_name'></el-table-column>
                <!-- 操作 -->
                <el-table-column align='center' label='操作' width='240px'>
                  <template v-slot='scope'>
                    <el-button type='primary' size='mini' icon='el-icon-edit' @click='updateParamsPull(scope.row)'>修改
                    </el-button>
                    <el-button type='danger' size='mini' icon='el-icon-delete' @click='delParams(scope.row)'>删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label='静态属性' name='only'>
            <el-button type='primary' size='small' :disabled='btnDisable' @click='addParamsPull'>添加属性</el-button>
            <div class='row-table'>
              <!-- 静态数据表格 -->
              <el-table :data='StaticData' border stripe>
                <el-table-column type='expand'>
                  <!-- 静态标签属性 -->
                  <template v-slot='scope'>
                    <el-tag v-for='(item,i) in scope.row.attr_vals' :key='i' closable @close='delTag(i,scope.row)'>
                      {{ item }}
                    </el-tag>
                    <!-- 动态生成一个属性节点 -->
                    <el-input
                      class='input-new-tag'
                      v-if='scope.row.inputTagVisible'
                      v-model='scope.row.inputTagValue'
                      ref='saveTagInput'
                      size='small'
                      @keyup.enter.native='InputTagConfirm(scope.row)'
                      @blur='InputTagConfirm(scope.row)'
                    >
                    </el-input>
                    <el-button v-else size='small' @click='showInputTag(scope.row)'>+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column label='#' type='index' align='center'></el-table-column>
                <el-table-column label='属性名称' align='center' prop='attr_name'></el-table-column>
                <el-table-column align='center' label='操作' width='240px'>
                  <template v-slot='scope'>
                    <el-button type='primary' size='mini' icon='el-icon-edit' @click='updateParamsPull(scope.row)'>修改
                    </el-button>
                    <el-button type='danger' size='mini' icon='el-icon-delete' @click='delParams(scope.row)'>删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-row>
        <!-- 添加属性弹出框 -->
        <el-dialog
          :title="'添加'+ addTitle"
          :visible.sync='addParamsVisible'
          @close='addFormClose'
          width='50%'>
          <el-form ref='addFormRef'
                   :model='addForm'
                   :rules='addFormRules'
                   label-width='100px'>
            <el-form-item :label='addTitle' prop='attr_name'>
              <el-input v-model='addForm.attr_name' @keyup.enter.native='addParams'></el-input>
            </el-form-item>
          </el-form>
          <span slot='footer' class='dialog-footer'>
    <el-button @click='addParamsVisible = false'>取 消</el-button>
    <el-button type='primary' @click='addParams'>确 定</el-button>
  </span>
        </el-dialog>
        <!-- 修改属性弹出框 -->
        <el-dialog
          :title="'修改'+addTitle"
          :visible.sync='updateParamsVisible'
          @close='updateFormClose'
          width='50%'>
          <el-form ref='updateFormRef'
                   :model='updateForm'
                   :rules='updateFormRules'
                   label-width='100px'>
            <el-form-item :label='addTitle' prop='attr_name'>
              <el-input v-model='updateForm.attr_name'></el-input>
            </el-form-item>
          </el-form>
          <span slot='footer' class='dialog-footer'>
    <el-button @click='updateParamsVisible = false'>取 消</el-button>
    <el-button type='primary' @click='updateParams'>确 定</el-button>
  </span>
        </el-dialog>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'CateParams',
  data() {
    return {
      shopList: [],
      // 级联选择框数据的双向绑定
      casShopKey: [],
      // 级联选择的数据项配置
      shopOption: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // Tab区域，默认选中的子项
      tabActive: 'many',
      // 保存静态属性的数据
      StaticData: [],
      // 保存动态参数的数据
      DynamicData: [],
      // 添加属性弹出框的显示与隐藏
      addParamsVisible: false,
      // 添加参数的数据双向绑定
      addForm: {
        attr_name: ''
      },
      // 验证添加表单的规则
      addFormRules: {
        attr_name: [
          { required: true, message: '参数名称必填', trigger: 'blur' }
        ]
      },
      // 修改属性弹出框的显示与隐藏
      updateParamsVisible: false,
      // 验证添加表单的规则
      updateFormRules: {
        attr_name: [
          { required: true, message: '参数名称必填', trigger: 'blur' }
        ]
      },
      // 修改参数时,该参数的信息
      updateForm: {
        attrId: '',
        attr_name: ''
      }
    }
  },
  created() {
    this.getShopList()
  },
  methods: {
    // 获取所有商品列表
    async getShopList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$msg.error('获取商品数据失败')
      }
      this.shopList = res.data
    },
    // 监听级联选择框的选择数据
    casShopKeys() {
      if (this.casShopKey.length !== 3) {
        this.casShopKey = []
        this.DynamicData = []
        this.StaticData = []
      } else {
        this.getParamsList()
      }
    },
    // Tabs区域切换触发的事件
    tabsClick() {
      if (this.casShopKey.length === 3) {
        this.getParamsList()
      }
    },
    // 获取参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(`categories/${ this.getThreeShopId }/attributes`, { params: { sel: this.tabActive } })
      if (res.meta.status !== 200) {
        return this.$msg.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(',') : []
        item.inputTagVisible = false
        item.inputTagValue = ''
      })
      if (this.tabActive === 'many') {
        this.DynamicData = res.data
      }
      if (this.tabActive === 'only') {
        this.StaticData = res.data
      }
    },
    // 拉起添加参数的弹出框
    addParamsPull() {
      this.addParamsVisible = true
    },
    // 发起添加参数名称请求
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${ this.getThreeShopId }/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.tabActive
        })
        if (res.meta.status !== 201) {
          return this.$msg.error('添加失败')
        }
        this.$msg.success('添加成功')
        this.addParamsVisible = false
        await this.getParamsList()
      })
    },
    // 关闭添加参数的弹出框后清除表单
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 拉起属性修改弹出框
    async updateParamsPull(scope) {
      const { data: res } = await this.$http.get(`categories/${ this.getThreeShopId }/attributes/${ scope.attr_id }`, {
        params: { attr_sel: this.tabActive }
      })
      if (res.meta.status !== 200) {
        return this.$msg.warning('没有获取到该参数信息')
      }
      this.updateForm.attrId = res.data.attr_id
      this.updateForm.attr_name = res.data.attr_name
      this.updateParamsVisible = true
    },
    // 发起修改参数名称请求
    updateParams() {
      this.$refs.updateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${ this.getThreeShopId }/attributes/${ this.updateForm.attrId }`, {
          attr_name: this.updateForm.attr_name,
          attr_sel: this.tabActive
        })
        if (res.meta.status !== 200) {
          return this.$msg.error('修改失败')
        }
        this.$msg.success('修改成功')
        this.updateParamsVisible = false
        await this.getParamsList()
      })
    },
    // 关闭添加参数的弹出框后清除表单
    updateFormClose() {
      this.$refs.updateFormRef.resetFields()
    },
    // 删除参数
    async delParams(scope) {
      const result = await this.$confirm('你确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return
      const { data: res } = await this.$http.delete(`categories/${ this.getThreeShopId }/attributes/${ scope.attr_id }`)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除失败')
      }
      this.$msg.success('删除成功')
      await this.getParamsList()
    },
    // 定义动态生成Tag标签属性的触发函数
    InputTagConfirm(row) {
      if (row.inputTagValue.trim().length === 0) {
        row.inputTagValue = ''
        row.inputTagVisible = false
      } else {
        row.attr_vals.push(row.inputTagValue)
        row.inputTagValue = ''
        row.inputTagVisible = false
        this.updateTags(row, '添加成功')
      }
    },
    // 发起请求更新标签参数
    async updateTags(row, msg) {
      const { data: res } = await this.$http.put(`categories/${ this.getThreeShopId }/attributes/${ row.attr_id }`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$msg.error(res.meta.msg)
      }
      this.$msg.success(msg)
    },
    // 点击删除对应的标签参数
    delTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.updateTags(row, '删除成功')
    },
    // 点击动态生成Tag时,显示输入框
    showInputTag(row) {
      row.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 添加属性按钮是否启用
    btnDisable() {
      return this.casShopKey.length !== 3
    },
    // 获取三级分类的ID
    getThreeShopId() {
      if (this.casShopKey.length === 3) {
        return this.casShopKey[2]
      }
      return null
    },
    // 添加属性的标题
    addTitle() {
      if (this.tabActive === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang='less' scoped>
.row-table {
  margin-top: 15px !important;
}

.el-tag {
  margin: 5px 10px;
}

.input-new-tag {
  width: 25%;
}
</style>
